package com.lyy.java_chatroom.api;

import com.lyy.java_chatroom.constant.Constant;
import com.lyy.java_chatroom.mapper.FriendMapper;
import com.lyy.java_chatroom.mapper.MessageMapper;
import com.lyy.java_chatroom.mapper.MessageSessionMapper;
import com.lyy.java_chatroom.mapper.UserMapper;
import com.lyy.java_chatroom.model.*;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserApi {
    @Resource
    private UserMapper userMapper;
    @Resource
    private FriendMapper friendMapper;
    @Resource
    private MessageSessionMapper messageSessionMapper;
    @Resource
    private MessageMapper messageMapper;

    //登录
    @PostMapping("/login")
    @ResponseBody
    public Result login(String userName, String password, HttpSession session){
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            return Result.fail("参数不合法");
        }
        User user=userMapper.selectByName(userName);
        if (user==null || !password.equals(user.getPassword())){
            return Result.fail("用户名或密码错误");
        }
        //传递进来的参数为session，如果没有的话会自动创建一个 相当于session=req.getSession(true)
        session.setAttribute(Constant.USER_SESSION_KEY,user);
        return Result.success(user);

    }

    //注册
    @PostMapping("register")
    @ResponseBody
    public Result register(String userName,String password,HttpSession session){
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            return Result.fail("参数不合法");
        }
        User user=new User();
        user.setUserName(userName);
        user.setPassword(password);
        try{
            if (userMapper.insert(user)==1){
                return Result.success(true);
            }
        }catch (DuplicateKeyException e){
            //名字重复，插入失败，insert()方法插入失败
            return Result.fail("该用户已注册");
        }
        return Result.fail("注册失败");
    }

    @GetMapping("/getuser")
    @ResponseBody//返回数据
    public Result getUser(HttpServletRequest req){
        HttpSession session= req.getSession(false);
        if (session==null){
            return Result.unlogin();//会话不存在，用户尚未登录
        }
        User user=null;
        try{
            user= (User) session.getAttribute(Constant.USER_SESSION_KEY);//空指针异常
            user.setPassword("");
            return Result.success(user);
        }catch (NullPointerException e){
            return Result.fail("未获取到此用户信息，请重新登录");
        }
    }

    @GetMapping("/getfriendlist")
    @ResponseBody
    public Result getFriendList(HttpServletRequest req){
        HttpSession session= req.getSession(false);
        if (session==null){
            return Result.unlogin();//会话不存在，用户尚未登录
        }
        User user=null;
        try {
            user= (User) session.getAttribute(Constant.USER_SESSION_KEY);//空指针异常
            List<Friend> friendList=friendMapper.selectFriendList(user.getUserId());
            return Result.success(friendList);
        }catch (NullPointerException e){
            return Result.fail("未获取到此用户信息，请重新登录");
        }
    }

    @GetMapping("/getsessionlist")
    @ResponseBody
    public Result getSessionList(HttpServletRequest req){
        //1、获取当前用户id
        HttpSession session=req.getSession(false);
        if (session==null){
            return Result.unlogin();//会话不存在，用户尚未登录
        }
        try {
            User user=(User) session.getAttribute(Constant.USER_SESSION_KEY);
            //2、根据userId查询该用户下的sessionId
            List<MessageSession> messageSessions=new ArrayList<>();
            List<Integer> sessionIds=messageSessionMapper.getSessionByUserId(user.getUserId());
            for (int sessionId:sessionIds) {
                MessageSession messageSession=new MessageSession();
                messageSession.setSessionId(sessionId);
                //3、根据sessionId找到对应的参与会话联系人（刨除登录用户）
                List<Friend> friends=messageSessionMapper.getFriendBySessionId(sessionId,user.getUserId());
                messageSession.setFriendList(friends);
                //4、根据会话id找到最后一条消息记录，需要设计好消息表
                String lastMessage=messageMapper.getLastMessageBySessionId(sessionId);
                if (lastMessage==null){
                    messageSession.setLastMessage("");
                }else {
                    messageSession.setLastMessage(lastMessage);
                }
                messageSessions.add(messageSession);
            }
            return Result.success(messageSessions);
        }catch (NullPointerException e){
            return Result.fail("未获取到此用户信息，请重新登录");
        }
    }

    /*
        创建新会话让服务器保存，让服务器的数据在2个表中记录数据
        张三-点击-李四
        1、message_session(session_id,last_time)：新增新会话记录，返回新会话的自增主键(session_id)
        2、message_session_user(session_id,user_id)：张三和新会话关联
        3、message_session_user(session_id,user_id)：李四和新会话关联
     */
    @PostMapping("/session")
    @ResponseBody
    public Result addMessageSession(int toUserId,HttpServletRequest req){
          HashMap<String,Integer> resp=new HashMap<>();
        try{
            HttpSession session=req.getSession(false);
            User fromUser=(User) session.getAttribute(Constant.USER_SESSION_KEY);
            //1、新增会话，获取新会话sesion_id放到对象messageSession中
            //MessageSession{int sessionId,List<Friend> friendList,String lastMessage}
            MessageSession messageSession=new MessageSession();
            messageSessionMapper.addMessageSession(messageSession);
            System.out.println("生成新会话："+messageSession.getSessionId());

            //2、张三和新会话关联
            //MessageSessionItem{int sesionId;int userId}
            MessageSessionItem item1=new MessageSessionItem();
            item1.setSessionId(messageSession.getSessionId());
            item1.setUserId(fromUser.getUserId());
            messageSessionMapper.addMessageSessionUser(item1);

            //3、李四和会话关联
            MessageSessionItem item2=new MessageSessionItem();
            item2.setSessionId(messageSession.getSessionId());
            item2.setUserId(toUserId);
            messageSessionMapper.addMessageSessionUser(item2);

            resp.put("sessionId",messageSession.getSessionId());
        }catch (NullPointerException e){
            return Result.fail("未获取到此用户信息，请重新登录");
        }
        return Result.success(resp);
    }
}















